package com.itheima.comment.service.impl;

import com.itheima.comment.docs.ApCommentDocument;
import com.itheima.comment.docs.ApCommentReplyDocument;
import com.itheima.comment.docs.ApCommentReplyLikeDocument;
import com.itheima.comment.docs.CommentReplyVo;
import com.itheima.comment.dto.CommentRelpyDto;
import com.itheima.comment.dto.CommentReplyLikeDto;
import com.itheima.comment.dto.CommentReplySaveDto;
import com.itheima.comment.pojo.ApCommentReply;
import com.itheima.comment.mapper.ApCommentReplyMapper;
import com.itheima.comment.service.ApCommentReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.pojo.PageInfo;
import com.itheima.common.util.RequestContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * APP评论回复信息表 服务实现类
 * </p>
 *
 * @author 作者
 * @since 2021-09-01
 */
@Service
public class ApCommentReplyServiceImpl extends ServiceImpl<ApCommentReplyMapper, ApCommentReply> implements ApCommentReplyService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /****
     * 保存评论回复
     * @param dto
     */
    @Override
    public void saveReply(CommentReplySaveDto dto) {
        //1:获取用户身份信息
        Integer userId = RequestContext.getNodeValue("id");
        String name = RequestContext.getNodeValue("name");

        //2：创建ApCommentReplyDocument对象，并完善
        ApCommentReplyDocument doc = new ApCommentReplyDocument();
        doc.setAuthorId(userId);
        doc.setAuthorName(name);
        doc.setCommentId(dto.getCommentId());
        doc.setContent(dto.getContent());
        doc.setLikes(0);
        doc.setCreatedTime(LocalDateTime.now());
        doc.setUpdatedTime(LocalDateTime.now());
        //3：将ApCommentReplyDocument对象保存到MongoDB
        mongoTemplate.save(doc);
        //3.1：回复的评论对象评论数量+1
        ApCommentDocument commentDoc = mongoTemplate.findById(doc.getCommentId(), ApCommentDocument.class);
        commentDoc.setReply(commentDoc.getReply()+1);
        mongoTemplate.save(commentDoc);
    }

    /**
     * 保存评论回复点赞/取消点赞
     * @param dto
     */
    @Override
    public void replyLike(CommentReplyLikeDto dto) {
        //1：获取用户信息
        Integer userId = RequestContext.getNodeValue("id");
        String name = RequestContext.getNodeValue("name");

        //2：点赞/取消点赞->点赞对象保存【点赞->添加，取消点赞->保存修改】
        ApCommentReplyLikeDocument likeDoc = new ApCommentReplyLikeDocument();
        likeDoc.setAuthorId(userId);
        likeDoc.setCommentReplyId(dto.getCommentReplyId());
        likeDoc.setOperation(dto.getOperation());
        mongoTemplate.save(likeDoc);


        //2.0:根据ID查询评论回复对象
        ApCommentReplyDocument doc = mongoTemplate.findById(dto.getCommentReplyId(), ApCommentReplyDocument.class);

        //2.1：点赞->点赞的评论回复点赞数+1
        if(dto.getOperation()==0){
            doc.setLikes(doc.getLikes()+1);
        }else{
            //2.2：取消点赞->点赞的评论回复点赞数-1
            doc.setLikes(doc.getLikes()-1);
        }
        mongoTemplate.save(doc);
    }

    /**
     * 评论回复列表查询
     * @param dto
     * @return
     */
    @Override
    public PageInfo<CommentReplyVo> loadReplyPage(CommentRelpyDto dto) {
        //2：分页查询评论回复列表
        //2.1:查询集合数据->排序【根据点赞数量排序】
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()));
        query.with(Sort.by(Sort.Direction.DESC,"likes"));
        query.with(PageRequest.of(dto.getPage().intValue()-1,dto.getSize().intValue()));
        List<ApCommentReplyDocument> replyDocs = mongoTemplate.find(query, ApCommentReplyDocument.class);

        //2.2：查询总数量
        Query countQuery = Query.query(Criteria.where("commentId").is(dto.getCommentId()));
        long count = mongoTemplate.count(countQuery, ApCommentReplyDocument.class);

        //获取评论回复ID集合
        List<CommentReplyVo> vos = new ArrayList<CommentReplyVo>();
        List<String> ids = new ArrayList<String>();
        for (ApCommentReplyDocument replyDoc : replyDocs) {
            CommentReplyVo vo = new CommentReplyVo();
            BeanUtils.copyProperties(replyDoc,vo);
            vos.add(vo);
            ids.add(replyDoc.getId());
        }

        //判断用户是否登录
        Boolean flag = RequestContext.getNodeValue("flag");
        if(flag){
            //1:获取用户信息
            Integer userId = RequestContext.getNodeValue("id");
            String name = RequestContext.getNodeValue("name");

            //3：如果用户登录了，则加载用户对当前回复点赞的信息
            //3.1:获取ID集合
            Query likeQuery = Query.query(Criteria.where("commentReplyId").in(ids).and("authorId").is(userId));
            List<ApCommentReplyLikeDocument> docs = mongoTemplate.find(likeQuery, ApCommentReplyLikeDocument.class);

            //判断是否对当前评论回复进行过点赞
            for (CommentReplyVo vo : vos) {
                for (ApCommentReplyLikeDocument doc : docs) {
                    if(doc.getCommentReplyId().equals(vo.getId())){
                        vo.setOperation(doc.getOperation());
                        break;
                    }
                }
            }
        }
        //4：封装分页对象，并返回
        Long pages = count%dto.getSize()==0?  count/dto.getSize() : count/dto.getSize()+1;
        PageInfo<CommentReplyVo> pageInfo = new PageInfo<CommentReplyVo>(dto.getPage(),dto.getSize(),count,pages,vos);
        return pageInfo;
    }
}